package com.iweb.education.Utils;

//Mysql（PreparedStatement）
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JdbcUtil {
    private static Connection conn = null;
    private static PreparedStatement stat = null;
    private static ResultSet rest = null;
    
    /*
    获取数据库连接
     */
    public static void getConn() {
        try {
            //加载数据库驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //创建数据库的连接
            conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/education","root","Typ1016.");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static Connection getCollection() throws SQLException{
        return DriverManager.getConnection("jdbc:mysql://localhost:3306/education","root","Typ1016.");
    }
    /*
    关闭资源
     */
    public static void closeSource() {
        try {
            if (conn != null)
                conn.close();
            if (stat != null)
                stat.close();
            if (rest != null)
                rest.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    
    
    /*
    查询
     */
    public static<E> List<Map<String, Object>> queryBySql(String sql,E... e) {
        List<Map<String, Object>> list = new ArrayList<>();
        getConn();
        try {
            stat = conn.prepareStatement(sql);
            for(int i =0;i<e.length;i++) {
                stat.setObject(i + 1, e[i]);
            }
            rest = stat.executeQuery();
            ResultSetMetaData rsmd = rest.getMetaData();
            while (rest.next()) {
                Map<String, Object> map = new HashMap<>();
                for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                    map.put(rsmd.getColumnName(i), rest.getObject(i));
                }
                list.add(map);
            }
        } catch (SQLException e1) {
            throw new RuntimeException(e1);
        }
        closeSource();
        return list;
    }
    
    /*
    增删改
     */
    public static<E> int updateBySql(String sql,E...e) {
        getConn();
        int res = 0;
        try {
            stat = conn.prepareStatement(sql);
            for(int i =0;i<e.length;i++) {
                stat.setObject(i + 1, e[i]);
            }
            res = stat.executeUpdate();
        } catch (SQLException e1) {
            throw new RuntimeException(e1);
        }
        closeSource();
        return res;
    }
}
